package com.javaio.demo.socket;

import java.io.*;
import java.net.Socket;

/**
 * 客户端
 */
public class Client1 {

    public static void main(String[] args) {
        final String TUICHU = "t";
        final String SERVER_IP = "127.0.0.1";
        final int SERVER_PROT = 8888;
        //客户端socket
        Socket socket = null;
        BufferedWriter writer = null;

        try {


            //创建客户端连接服务端
            socket = new Socket(SERVER_IP, SERVER_PROT);
            //创建io流
            //读取服务端发送过来的消息 输入
            BufferedReader reader = new BufferedReader(
                    new InputStreamReader(socket.getInputStream())
            );
            //向服务端发送消息 输出
            writer = new BufferedWriter(
                    new OutputStreamWriter(socket.getOutputStream())
            );

            //等待用户输入信息
            BufferedReader consolReader = new BufferedReader(
                    new InputStreamReader(System.in)
            );
            while (true) {
                String input = consolReader.readLine();
                writer.write(input + "\n");
                //缓冲区 避免资源消耗
                writer.flush();
                //获取服务端消息
                String msg = reader.readLine();
                if (null != msg) {
                    System.out.println("服务端" + socket.getPort() + "发送的消息" + msg);
                }
                if (TUICHU.equals(input)) {
                    break;
                }
            }

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //关闭socket
            if (null != writer) {
                try {
                    //关闭了writer  也就关闭了socket
                    writer.close();
                } catch (IOException e) {
                    e.printStackTrace();
                    System.out.println("socket关闭异常");
                }
            }
        }

    }
}